#include <ArduinoJson.h>
#include <ArduinoJson.hpp>

#include <DHT11.h>
#include <ESP8266WiFi.h>  
#include <PubSubClient.h>  

// Create an instance of the DHT11 class.
// - For Arduino: Connect the sensor to Digital I/O Pin 2.
// - For ESP32: Connect the sensor to pin GPIO2 or P2.
// - For ESP8266: Connect the sensor to GPIO2 or D4.
DHT11 dht11(2);



// WiFi设置  
//const char* ssid = "HUAWEI_B311_9D0F";  
//const char* password = "fangzhengguoji666";  

const char* ssid = "tp-hu";  
const char* password = "huHangFei716";  
  
// MQTT服务器设置  
const char* mqtt_server = "47.94.212.176";  
//const char* mqtt_server = "192.168.1.115";
const int mqtt_port = 28889;  
const char* mqtt_client_id = "transducer-3DKQ6UME2eP9EMipVY0X3tQrwiq0TnBh";  
const char* mqtt_user_name = "user01";  
const char* mqtt_password = "aey3DNK8hMr2XgD0RjhBH4HasYVxA6YLHPfSQdfp6rU31z8p2uUyKZKirheyWiqY";  
const char* mqtt_sub_all_topic = "gardener/iot/mqtt/subscribe/data/all";  
const char* mqtt_sub_self_topic = "gardener/iot/mqtt/subscribe/data/transducer-3DKQ6UME2eP9EMipVY0X3tQrwiq0TnBh";  
const char* mqtt_pub_topic = "gardener/iot/mqtt/publish/data/"; 

String receiveMsg = "";
WiFiClient espClient;  
PubSubClient client(espClient);  

void setup_wifi() {  
  delay(10);  
  // 连接到WiFi网络  
  Serial.print("Connecting to ");  
  Serial.println(ssid);  
  WiFi.begin(ssid, password);  
  
  while (WiFi.status() != WL_CONNECTED) {  
    delay(500);  
    Serial.print(".");  
  }  
  
  Serial.println("");  
  Serial.println("WiFi connected");  
  Serial.print("IP address: ");  
  Serial.println(WiFi.localIP());  
}  
  
void reconnect() {  
  // Loop until we're reconnected  
  while (!client.connected()) {  
    Serial.print("Attempting MQTT connection...");  
    // 连接到MQTT服务器  
    if (client.connect(mqtt_client_id,mqtt_user_name,mqtt_password)) {  
      Serial.println("connected");  
      // 一旦连接，订阅主题  
      client.subscribe(mqtt_sub_all_topic);  
      client.subscribe(mqtt_sub_self_topic);  
    } else {  
      delay(5000);  
    }  
  }  
}  
  
void callback(char* topic, byte* payload, unsigned int length) {  
  receiveMsg="";
  // 处理接收到的消息  
  Serial.print("Message arrived [");  
  Serial.print(topic);  
  Serial.print("] ");  
  for (int i = 0; i < length; i++) {  
    Serial.print((char)payload[i]);
    receiveMsg.concat((char)payload[i]);
  }  
  Serial.println();  
}  

void setup() {
    // Initialize serial communication to allow debugging and data readout.
    // Using a baud rate of 9600 bps.
    Serial.begin(9600);
    // Uncomment the line below to set a custom delay between sensor readings (in milliseconds).
    dht11.setDelay(3000); // Set this to the desired delay. Default is 500ms.
    setup_wifi();  
    client.setServer(mqtt_server, mqtt_port);  
    client.setCallback(callback);  
    
}
StaticJsonDocument<100> jsonBuffer;
void loop() {

    if (!client.connected()) {  
        reconnect();  
    }  
    client.loop();  

    int temperature = 0;
    int humidity = 0;

    // Attempt to read the temperature and humidity values from the DHT11 sensor.
    int result = dht11.readTemperatureHumidity(temperature, humidity);
   
    // Check the results of the readings.
    // If the reading is successful, print the temperature and humidity values.
    // If there are errors, print the appropriate error messages.
    if (result == 0) {
         jsonBuffer["h"]=humidity;
         jsonBuffer["t"]=temperature;
         //jsonBuffer["s"]=0;
         //jsonBuffer["m"]="ok";
        //Serial.print("temperature :");
        //Serial.print(temperature);
        //Serial.print("humidity :");
        //Serial.print(humidity);
    } else {
        // Print error message based on the error code.
        Serial.println(DHT11::getErrorString(result));
         //jsonBuffer["s"]=result;
        //jsonBuffer["m"]=DHT11::getErrorString(result);
    }
    // jsonBuffer["ti"]=millis();
     //Serial.print("time");
    //Serial.println(millis());
    // jsonBuffer["l"]=receiveMsg;
    String jsonData;
    serializeJson(jsonBuffer, jsonData); 
    // Serial.print("send mqtt");
     Serial.print(jsonData);
    char charArray[jsonData.length() + 1]; // 创建足够大的char数组
    jsonData.toCharArray(charArray, jsonData.length() + 1); // 将String转换为char数组
    client.publish(mqtt_pub_topic, charArray); 
}